package com.wuax.service.impl;

import com.wuax.domain.LoginUser;
import com.wuax.domain.SysUser;
import com.wuax.domain.vo.Result;
import com.wuax.mapper.SysUserMapper;
import com.wuax.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public Result login(LoginUser loginUser, HttpSession session) {
        // 获取用户名和密码
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        // 判断两者是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Result.error("请填写正确的用户名或密码");
        }
        // 通过用户名和密码查询数据库中是否有该用户
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setPassword(password);
        List<SysUser> users = sysUserMapper.select(sysUser);
        // 如果有该用户则登录，并赋值user信息，否则登录失败
        if (users != null && users.size() == 1) {
            SysUser user = users.get(0);
            session.setAttribute("sys_user", user);
            return Result.success("登录成功", user);
        }
        return Result.error("登录失败");
    }
}
